/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package MyOwnChat;

import java.net.*;
import java.io.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;


// Lubinchat new class= chat
/**
 *
 * @author lubinchen
 */
public class Lubinchat extends Thread {
    //      172.60.25.3:4000
    //      196.128.3.25:4000
     private ServerSocket   server = null;
     private LubinServerThread clients[] = new LubinServerThread[50];
     private int            clientCount = 0;
     private Thread     thread    = null;
     public  Lubinchat            chat  =null;
     private DataInputStream  streamIn  =  null;
     private DataOutputStream streamOut = null;
     private boolean addmyself=true;
     public  InetAddress realip=null;
     public  int port=4000;
     public  int t=0;
     private InetAddress ownIP=null;
     private Socket tempSocket=null;
     public  ArrayList<String> onlinenames=null;
     public  ArrayList<String> onlineIP=null;




     //public   String DestinationIP="172.17.38.247";


    public Lubinchat()
    {

        onlinenames = new ArrayList<String>(0);
        onlineIP = new ArrayList<String>(0);

        onlinenames.add("LubinMac");
        onlineIP.add("172.17.38.247");

        onlinenames.add("LubinWindows");
        onlineIP.add("192.168.79.128");

        /*
        onlinenames.add("");
        onlineIP.add("");

        onlinenames.add("");
        onlineIP.add("");   */


        NewServer(port);

        // get myown IP

        try{
		ownIP=InetAddress.getLocalHost();
		System.out.println("IP of my own system is := "+ownIP.getHostAddress());
                System.out.println("\n");

	}catch (Exception e){
	System.out.println("Exception caught at setting up client "+e.getMessage());}


        for(int n=0;n<onlineIP.size();n++)
        {

            System.out.println("at checking n= "+n+" name= "+onlinenames.get(n));
            if(onlineIP.get(n) == null ? ownIP.getHostAddress() != null : !onlineIP.get(n).equals(ownIP.getHostAddress())){


                //pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp
                try{
                    System.out.println("@ trying n= "+n+" name= "+onlinenames.get(n));
                     Thread thread1 = new Thread(new ChatClient(InetAddress.getByName(onlineIP.get(n)), port, onlinenames.get(n) ));
                     thread1.run();
                    }catch (Exception e){System.out.println("Exception caught at adding a client "+ onlinenames.get(n) +" because: "+e.getMessage());}
            }
        }

    }





    private void NewServer(int port)
    {


        try
          {  System.out.println("Binding to port of number " + port + ", please wait  ...");
             server = new ServerSocket(port);
             System.out.println("Server started  !");
             System.out.println("\n");
          }
          catch(IOException ioe)
          {  System.out.println("Can not bind to port " + port + ": " + ioe.getMessage()); }
    }


    private String findOnlineName(String IP){

        String Name="Unregistered User";

        for(int n=0;n<onlineIP.size();n++){
            if(IP.equals(onlineIP.get(n)))
                Name=onlinenames.get(n);
            
        }
        return Name;
    }



    public void run(){

         while(true){

          System.out.println("\n");
            System.out.println("Waiting for a client ........................................");

           try
           {
                tempSocket=server.accept();
                addThread("noName", tempSocket);
           }
           catch(IOException ioe) {  System.out.println("Server accept error: " + ioe);  }

         }
    }



  private void addThread(String name,Socket socket)
   {
             name=findOnlineName(socket.getInetAddress().getHostAddress());

             System.out.println("@addThread");
             System.out.println("found name for IP= " + socket.getInetAddress().getHostAddress()+"name=" +name);
             //System.out.println("New client Thread created for IP= " + name);
             clients[clientCount] = new LubinServerThread(name, socket, this, clientCount);

             try{
                clients[clientCount].open();
                clients[clientCount].start();
                clientCount++;
              } catch (IOException ioe) {System.out.println("cannot open and start new thread");};


             
   }

   private int findClient(String ipstring)
   {  for (int i = 0; i < clientCount; i++)
         if (clients[i].socket.getInetAddress().getHostAddress().equals(ipstring))
            return i;
      return -1;
   }


   public synchronized void handle(String name, String input)
   {
        if (input.equals(".bye"))
      {  clients[findClient(name)].send(".bye");
         remove(name); }
      else
         for (int i = 0; i < clientCount; i++)
            clients[i].send("From"+name + ": " + input);
   }



     public synchronized void remove(String name)
   {  int pos = findClient(name);
      if (pos >= 0)
      {  LubinServerThread toTerminate = clients[pos];
         System.out.println("Removing client thread " + name + " at client list index= " + pos);
         if (pos < clientCount-1)
            for (int i = pos+1; i < clientCount; i++)
               clients[i-1] = clients[i];
         clientCount--;
         try
         {  toTerminate.close(); }
         catch(IOException ioe)
         {  System.out.println("Error closing thread: " + ioe); }
         toTerminate.stop();
      }
   }


   public static void main(String args[]) {
        Lubinchat chat=new Lubinchat();
        chat.start();
   }


}
